package leetcode.每日一题.并查集;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ：zsy
 * @date ：Created 2022/12/19 7:51 PM
 * @description：
 */
public class 寻找图中是否存在路径 {

    @Test
    public void test() {

    }

    /*class Solution {
        public boolean validPath(int n, int[][] edges, int source, int destination) {
            UnionFind unionFind = new UnionFind(n);
            for (int[] edge : edges) {
                unionFind.uni(edge[0], edge[1]);
            }
            return unionFind.isConnect(source, destination);
        }
    }

    class UnionFind {
        private int[] parent;
        private int[] rank;
        public UnionFind(int n) {
            parent = new int[n];
            rank = new int[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
            }
        }

        public void uni(int x, int y) {
            int rootx = find(x);
            int rooty = find(y);
            if (rootx != rooty) {
                if (rank[rootx] > rank[rooty]) {
                    parent[rooty] = rootx;
                } else if (rank[rootx] < rank[rooty]) {
                    parent[rootx] = rooty;
                } else {
                    parent[rooty] = rootx;
                    rank[rootx]++;
                }
            }
        }

        private int find(int x) {
            if (x != parent[x]) {
                parent[x] = find(parent[x]);
            }
            return parent[x];
        }

        public boolean isConnect(int x, int y) {
            return find(x) == find(y);
        }
    }*/

    class Solution {
        public boolean validPath(int n, int[][] edges, int source, int destination) {
            List<Integer>[] adj = new List[n];
            for (int i = 0; i < n; i++) {
                adj[i] = new ArrayList<>();
            }
            for (int[] edge : edges) {
                adj[edge[0]].add(edge[1]);
                adj[edge[1]].add(edge[0]);
            }
            boolean[] visited = new boolean[n];
            return dfs(adj, visited, source, destination);
        }

        private boolean dfs(List<Integer>[] adj, boolean[] visited, int source, int destination) {
            if (source == destination) {
                return true;
            }
            visited[source] = true;
            for (Integer next : adj[source]) {
                if (!visited[next] && dfs(adj, visited, next, destination)) {
                    return true;
                }
            }
            return false;
        }

    }
}
